<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { Plus, Lock, Edit, Delete } from '@element-plus/icons-vue';

const { t } = useI18n();

type TrustedSite = {
  id: string;
  ip: string;
  createdAt: string;
  updatedAt: string;
};

const trustedSitesList = ref<TrustedSite[]>([]);
const loading = ref(false);
const editDialogVisible = ref(false);
const editingCertificate = ref<TrustedSite | null>(null);
const editFormRef = ref();
const editForm = reactive({
  ip: ''
});
const tableHeight = computed(() => {
  return 'calc(100vh - 120px)';
});

const editFormRules = computed(() => ({
  ip: [
    { required: true, message: t('LOGIN_IP_REQUIRED'), trigger: 'blur' },
    {
      pattern: /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,
      message: t('LOGIN_IP_INVALID'),
      trigger: 'blur'
    }
  ]
}));

const loadTrustedSitesList = async () => {
  loading.value = true;
  try {
    const result = await window.api.dialog.getTrustedSitesList();
    if (result.success && result.certificates) {
      trustedSitesList.value = result.certificates;
    } else {
      ElMessage.error((result as any).error || t('HOME_TRUST_LIST_LOAD_FAILED'));
    }
  } catch (error) {
    ElMessage.error(t('HOME_TRUST_LIST_LOAD_FAILED'));
  } finally {
    loading.value = false;
  }
};

const handleAdd = () => {
  editingCertificate.value = null;
  editForm.ip = '';
  editDialogVisible.value = true;
};

const handleEdit = (cert: TrustedSite) => {
  editingCertificate.value = cert;
  editForm.ip = cert.ip;
  editDialogVisible.value = true;
};

const handleSave = async () => {
  if (!editFormRef.value) {
    return;
  }

  const valid = await editFormRef.value.validate();
  if (!valid) {
    return;
  }

  try {
    if (editingCertificate.value?.id) {
      const result = await window.api.dialog.updateTrustedSite(
        editingCertificate.value.id,
        editForm.ip
      );
      if (result.success) {
        ElMessage.success(t('HOME_TRUST_LIST_UPDATE_SUCCESS'));
        await loadTrustedSitesList();
        editDialogVisible.value = false;
      } else {
        ElMessage.error((result as any).error || t('HOME_TRUST_LIST_UPDATE_FAILED'));
      }
    } else {
      const result = await window.api.dialog.addTrustedSite(editForm.ip);
      if (result.success) {
        ElMessage.success(t('HOME_TRUST_LIST_ADD_SUCCESS'));
        await loadTrustedSitesList();
        editDialogVisible.value = false;
      } else {
        ElMessage.error((result as any).error || t('HOME_TRUST_LIST_ADD_FAILED'));
      }
    }
  } catch (error) {
    console.error('Failed to save trusted site:', error);
    ElMessage.error(t('HOME_TRUST_LIST_SAVE_FAILED'));
  }
};

const handleDelete = async (cert: TrustedSite) => {
  try {
    await ElMessageBox.confirm(
      t('HOME_TRUST_LIST_DELETE_CONFIRM', { label: cert.ip }),
      t('HOME_TRUST_LIST_DELETE_TITLE'),
      {
        confirmButtonText: t('HOME_DELETE'),
        cancelButtonText: t('HOME_CANCEL'),
        type: 'warning'
      }
    );

    const result = await window.api.dialog.deleteTrustedSite(cert.id, cert.ip);

    if (result.success) {
      ElMessage.success(t('HOME_TRUST_LIST_DELETE_SUCCESS'));
      await loadTrustedSitesList();
    } else {
      ElMessage.error((result as any).error || t('HOME_TRUST_LIST_DELETE_FAILED'));
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Failed to delete trusted site:', error);
      ElMessage.error(t('HOME_TRUST_LIST_DELETE_FAILED'));
    }
  }
};

onMounted(() => {
  loadTrustedSitesList();
});
</script>

<template>
  <div class="trusted-sites-list-page">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ t('HOME_TRUST_LIST_TITLE') }}</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" class="add-btn" @click="handleAdd">
          {{ t('HOME_TRUST_LIST_ADD') }}
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <div v-if="loading" class="loading-container">
        <el-loading :loading="loading" />
      </div>
      <div v-else-if="trustedSitesList.length === 0" class="empty-container">
        <el-icon class="empty-icon"><Lock /></el-icon>
        <p class="empty-text">{{ t('HOME_TRUST_LIST_EMPTY') }}</p>
      </div>
      <div v-else class="table-container">
        <el-table
          :data="trustedSitesList"
          style="width: 100%; height: 100%"
          stripe
          class="trust-table"
          :height="tableHeight"
        >
          <el-table-column prop="ip" :label="t('LOGIN_IP')" width="200" />
          <el-table-column :label="t('HOME_ACTIONS')" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                link
                :icon="Edit"
                class="action-btn edit-btn"
                @click="handleEdit(scope.row)"
              >
                {{ t('HOME_EDIT') }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                link
                :icon="Delete"
                class="action-btn delete-btn"
                @click="handleDelete(scope.row)"
              >
                {{ t('HOME_DELETE') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 编辑/添加-->
    <el-dialog
      v-model="editDialogVisible"
      :title="editingCertificate?.id ? t('HOME_TRUST_LIST_EDIT') : t('HOME_TRUST_LIST_ADD')"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
        <el-form-item :label="t('LOGIN_IP')" prop="ip">
          <el-input v-model="editForm.ip" :placeholder="t('LOGIN_IP_PLACEHOLDER')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          {{ t('HOME_CANCEL') }}
        </el-button>
        <el-button type="primary" @click="handleSave">
          {{ t('HOME_SAVE') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.trusted-sites-list-page {
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
  box-sizing: border-box;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;

    .header-title {
      display: flex;
      align-items: center;
      gap: 12px;

      .title-icon {
        font-size: 24px;
        color: #303133;
      }

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
        color: #303133;
        background: #303133;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;

      .add-btn {
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);

        &:hover {
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
        }
      }
    }
  }

  .page-content {
    flex: 1;
    overflow: hidden;
    background: #ffffff;
    display: flex;
    flex-direction: column;
    min-height: 0;
    width: 100%;
    margin: 0;
    padding: 0;

    .loading-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }

    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      text-align: center;

      .empty-icon {
        font-size: 64px;
        color: #c0c4cc;
        margin-bottom: 20px;
        opacity: 0.6;
      }

      .empty-text {
        font-size: 16px;
        color: #909399;
        margin-bottom: 24px;
      }

      .empty-add-btn {
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);

        &:hover {
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
        }
      }
    }

    .table-container {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      padding: 0;
      margin: 0;
      width: 100%;

      .trust-table {
        flex: 1;
        height: 100%;
        width: 100%;
        margin: 0;

        :deep(.el-table) {
          width: 100% !important;
          margin: 0 !important;
        }

        :deep(.el-table__inner-wrapper) {
          width: 100% !important;
        }

        :deep(.el-table__header-wrapper) {
          flex-shrink: 0;
          width: 100% !important;
          margin: 0;
        }

        :deep(.el-table__body-wrapper) {
          flex: 1;
          overflow-y: auto;
          width: 100% !important;
          margin: 0;
        }

        :deep(.el-table__header) {
          width: 100% !important;
          margin: 0;

          th {
            background: #f5f7fa;
            color: #606266;
            font-weight: 600;
            padding: 16px 0;
          }
        }

        :deep(.el-table__body) {
          width: 100% !important;
          margin: 0;
        }

        :deep(.el-table__row) {
          width: 100% !important;
          margin: 0;

          &:hover {
            background: #f5f7fa;
          }
        }

        :deep(.el-table__cell) {
          padding: 16px 0;
        }
      }

      .action-btn {
        margin-right: 8px;
        background: transparent !important;
        box-shadow: none;

        &:focus,
        &:active,
        &:focus-visible {
          background: transparent !important;
          box-shadow: none;
          outline: none;
        }

        &.edit-btn {
          color: #409eff;

          :deep(.el-icon) {
            color: #409eff;
          }

          &:hover {
            color: #66b1ff;

            :deep(.el-icon) {
              color: #66b1ff;
            }
          }
        }

        &.delete-btn {
          color: #f56c6c;

          :deep(.el-icon) {
            color: #f56c6c;
          }

          &:hover {
            color: #f78989;

            :deep(.el-icon) {
              color: #f78989;
            }
          }
        }
      }
    }
  }
}

// 自定义滚动条
.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;

  &:hover {
    background: #a8a8a8;
  }
}
</style>
